<?php

class ServerController extends CommonController {

	public function __construct() {
		parent::__construct();
	}

	public function recordsAction() {
		$page = (int) $this->requestGet('page', 1);
		$pageSize = (int) $this->requestGet('pageSize', 100);
		$offset = ($page - 1) * $pageSize;

		$totalQuery = "SELECT COUNT(`id`) as `total` FROM `server`";
		$db = $this->loadSqlite('bamboo');
		$totalRow = $db->getOne($totalQuery);
		$data = array('total' => $totalRow['total']);
		
		$query = "SELECT * FROM `server` LIMIT {$offset}, {$pageSize}";
		$data['records'] = $db->getAll($query);

		$this->jsonSuccess('', $data);
	}

	public function findAction() {
		$id = (int) $this->requestGet('id');
		if (!$id)
			$this->jsonError('参数错误');
		$findQuery = "SELECT * FROM `server` WHERE `id`={$id}";
		$db = $this->loadSqlite('bamboo');
		$row = $db->getOne($findQuery);
		$this->jsonSuccess('', $row);
	}

	public function setAction(){
		$id = (int) $this->requestPost('id');

		$data = array(
			'name' => $this->requestPost('name'),
			'url' => $this->requestPost('url'),
			'ip' => $this->requestPost('ip')
		);

		$db = $this->loadSqlite('bamboo');

		if ($db->set('server', $data, $id)) {
			$this->jsonSuccess('保存成功');
		} else {
			$this->jsonError('保存失败 ' . $db->errorMessage);
		}
	}


	public function deleteAction() {
		$id = (int) $this->request('id');
		if (!$this->exists($id)) {
			$this->jsonError('保存失败');
		}
		$db = $this->loadSqlite('bamboo');
		$query = "DELETE FROM `server` WHERE `id`={$id}";
		if ($db->exec($query)) {
			$this->jsonSuccess('删除成功');
		} else {
			$this->jsonError('删除失败');
		}
	}

	private function exists($id) {
		$db = $this->loadSqlite('bamboo');
		$findQuery = "SELECT COUNT(*) as `count` FROM `server` WHERE `id`={$id}";
		$row = $db->getOne($findQuery);
		return $row['count'] > 0;
	}
}

?>
